<template>
    <el-dialog :close-on-click-modal="false" :title="titleMap[mode]" v-model="visible" :width="900" destroy-on-close @closed="$emit('closed')" custom-class="notpt">
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px" label-position="right" v-loading="loading">
            <el-tabs v-model="activeName">
                <el-tab-pane label="基础信息" name="first" style="margin-top: 20px;">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="头像" prop="portrait">
                                <sc-upload v-model="form.portrait" title="上传头像" cropper :aspectRatio="1/1"></sc-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="姓名" prop="name">
                                <el-input v-model="form.name" placeholder="请输入姓名" clearable :maxlength="20" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="手机号" prop="mobile">
                                <el-input v-model="form.mobile" placeholder="请输入手机号" clearable :maxlength="11" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="生日" prop="birthday">
                                <el-date-picker
                                    style="width: 100%;"
                                    v-model="form.birthday"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    type="date"
                                    placeholder="选择日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="状态" prop="status">
                                <el-radio-group v-model="form.status">
                                    <el-radio :label="1">启用</el-radio>
                                    <el-radio :label="0">禁用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="性别" prop="gender">
                                <el-radio-group v-model="form.gender">
                                    <el-radio :label="1">男</el-radio>
                                    <el-radio :label="2">女</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="年级" prop="gradeId">
                                <el-select v-model="form.gradeId" placeholder="请选择" style="width: 100%;">
                                    <el-option :label="item.name" :value="item.id" v-for="item in gradeList"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="学校" prop="school">
                                <el-input v-model="form.school" placeholder="请输入学校" clearable :maxlength="50" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="密码" prop="password">
                                <el-input v-model="form.password" type="password" placeholder="请输入密码" clearable :maxlength="15" show-word-limit show-password></el-input>
                                <div class="" style="font-size:12px;line-height:2;padding-top:0px;color:#999;">
								   默认密码为手机号后6位，不输入密码则不修改密码
							    </div>
                            </el-form-item>
                           
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="选填信息" name="second" style="margin-top: 20px;">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="体验教练" prop="trialTeacherId">
                                <el-select
                                style="width: 100%;"
                                v-model="form.trialTeacherId"
                                filterable
                                remote
                                clearable
                                placeholder="请输入教练名称搜索"
                                :remote-method="searchTeacherHander"
                                :loadings="teacherLoading">
                                    <el-option
                                        v-for="item in teacherList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                        :disabled="item.disabled">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="父亲职业" prop="fatherWork">
                                <el-input v-model="form.fatherWork" placeholder="请输入父亲职业" clearable :maxlength="50" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="家庭住址" prop="address">
                                <el-input v-model="form.address" placeholder="请输入家庭住址" clearable :maxlength="100" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="语文成绩" prop="chineseScore">
                                <el-input v-model="form.chineseScore" placeholder="请输入语文成绩" clearable >
                                    <template #append>分</template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="班级排名" prop="classRank">
                                <el-input v-model="form.classRank" placeholder="请输入班级排名" clearable >
                                    <template #append>名</template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="补习情况" prop="extraStudy">
                                <el-select v-model="form.extraStudy" placeholder="请选择" style="width: 100%;">
                                    <el-option label="曾经补习" :value="1"></el-option>
                                    <el-option label="正在补习" :value="2"></el-option>
                                    <el-option label="从未补习" :value="3"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="生源信息" prop="source">
                                <el-select v-model="form.source" placeholder="请选择" style="width: 100%;">
                                    <el-option label="招生信息" :value="1"></el-option>
                                    <el-option label="朋友推荐" :value="2"></el-option>
                                    <el-option label="转介绍" :value="3"></el-option>
                                    <el-option label="其他" :value="4"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="体验时长" prop="trialDuration">
                                <el-input v-model="form.trialDuration" placeholder="请输入体验时长" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="首测词汇量" prop="vocabulary">
                                <el-input v-model="form.vocabulary" placeholder="请输入首测词汇量" clearable></el-input>
                            </el-form-item>
                           
                            <el-form-item label="正确率" prop="accuracyRate">
                                <el-input v-model="form.accuracyRate" placeholder="请输入正确率" clearable>
                                    <template #append>%</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="体验日期" prop="">
                                <el-date-picker
                                    style="width: 100%;"
                                    v-model="form.trialDate"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    type="date"
                                    placeholder="选择日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="母亲职业" prop="motherWork">
                                <el-input v-model="form.motherWork" placeholder="请输入母亲职业" clearable :maxlength="50" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="英语成绩" prop="englishScore">
                                <el-input v-model="form.englishScore" placeholder="请输入英语成绩" clearable >
                                    <template #append>分</template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="数学成绩" prop="mathScore">
                                <el-input v-model="form.mathScore" placeholder="请输入数学成绩" clearable >
                                    <template #append>分</template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="年级排名" prop="gradeRank">
                                <el-input v-model="form.gradeRank" placeholder="请输入年级排名" clearable >
                                    <template #append>名</template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="学习兴趣" prop="learningInterest">
                                <el-select v-model="form.learningInterest" placeholder="请选择" style="width: 100%;">
                                    <el-option label="有" :value="1"></el-option>
                                    <el-option label="无" :value="2"></el-option>
                                    <el-option label="一般" :value="3"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="英语水平" prop="englishLevel">
                                <el-input v-model="form.englishLevel" placeholder="请输入英语水平" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="记住词汇" prop="rememberWords">
                                <el-input v-model="form.rememberWords" placeholder="请输入记住词汇" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="推荐人" prop="recommender">
                                <el-input v-model="form.recommender" placeholder="请输入推荐人" clearable :maxlength="50" show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="备注" prop="remark">
                                <el-input type="textarea" rows="4" v-model="form.remark" placeholder="请输入备注" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-tab-pane>
            </el-tabs>
           
        </el-form>
        <template #footer>
            <el-button @click="visible=false">取 消</el-button>
            <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
        </template>
    </el-dialog>
</template>

<script>
import { checkMobile } from '@/utils/validate'
export default {
    emits: ['success', 'closed'],
    props: {
        rolelist: { type: Array, default: () => [] },
    },
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增学员',
                edit: '编辑学员',
                show: '查看'
            },
            visible: false,
            loading: false,
            agentLoading: false,
            teacherLoading: false,
            isSaveing: false,
            activeName: 'first',
            form: this.getDefaultRuleForm(),
            rules: {
                portrait: [
                    { required: false, message: '请上传头像' }
                ],
                name: [
                    { required: true, message: '请输入姓名' }
                ],
                password: [
                    { required: false, message: '请输入密码' },
                    { min: 6, max: 15, message: '密码为6-15位', trigger: 'blur'}
                ],
                mobile: [
                    { required: true, validator: checkMobile }
                ],
                birthday: [
                    { required: false, message: '请选择生日' },
                ],
                school: [
                    { required: true, message: '请输入学校' }
                ],
                gradeId: [
                    { required: true, message: '请选择年级', trigger: 'change'  },
                ],
                chineseScore: [
                    { required: false, message: '请输入语文成绩', trigger: 'blur' },
                    { pattern: /^0\.([0-9]|\d[0-9])$|^[0-9]\d{0,8}\.\d{0,2}$|^[0-9]\d{0,8}$/, message: '分数最多只能为2位小数', trigger: 'blur'},
                ],
                mathScore: [
                    { required: false, message: '请输入数学成绩', trigger: 'blur' },
                    { pattern: /^0\.([0-9]|\d[0-9])$|^[0-9]\d{0,8}\.\d{0,2}$|^[0-9]\d{0,8}$/, message: '分数最多只能为2位小数', trigger: 'blur'},
                ],
                englishScore: [
                    { required: false, message: '请输入英语成绩', trigger: 'blur' },
                    { pattern: /^0\.([0-9]|\d[0-9])$|^[0-9]\d{0,8}\.\d{0,2}$|^[0-9]\d{0,8}$/, message: '分数最多只能为2位小数', trigger: 'blur'},
                ],
                classRank: [
                    { required: false, message: '请输入班级排名', trigger: 'blur' },
                    { pattern: /^(-|[0-9])\d*$/, message: '只能输入整数', trigger: 'blur'},
                ],
                gradeRank: [
                    { required: false, message: '请输入年级排名', trigger: 'blur' },
                    { pattern: /^(-|[0-9])\d*$/, message: '只能输入整数', trigger: 'blur'},
                ],
                vocabulary: [
                    { required: false, message: '请输入首测词汇量', trigger: 'blur' },
                    { pattern: /^(-|[0-9])\d*$/, message: '只能输入整数', trigger: 'blur'},
                ],
                trialDuration: [
                    { required: false, message: '请输入体验时长', trigger: 'blur' },
                    { pattern: /^0\.([0-9]|\d[0-9])$|^[0-9]\d{0,8}\.\d{0,2}$|^[0-9]\d{0,8}$/, message: '只能为数字且最多只有2位小数', trigger: 'blur'},
                ],
                rememberWords: [
                    { required: false, message: '请输入记住词汇', trigger: 'blur' },
                    { pattern: /^(-|[0-9])\d*$/, message: '只能输入整数', trigger: 'blur'},
                ],
                accuracyRate: [
                    { required: false, message: '请输入正确率', trigger: 'blur' },
                    { pattern: /^0\.([0-9]|\d[0-9])$|^[0-9]\d{0,8}\.\d{0,2}$|^[0-9]\d{0,8}$/, message: '只能为数字且最多只能为2位小数', trigger: 'blur'},
                ]
            },
            agentList: [],
            teacherList: [],
            gradeList: []
        }
    },
    mounted() {
        this.searchAgentHander()
        this.searchTeacherHander()
        this.getGradeList()
    },
    methods: {
        //显示
        open(mode = 'add') {
            this.mode = mode;
            if (mode == 'add') {
                this.resetForm()
            }
            this.visible = true;
            return this
        },
        resetForm() {
            this.form = this.getDefaultRuleForm()
        },
        getGradeList() {
            this.$API.user.grade.all.get().then(res => {
                this.gradeList = res.data
            })
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (!valid) {
                    return false
                }
                try {
                    this.isSaveing = true;
                    if (this.mode == 'add') {
                        await this.$API.user.action.post(this.form).then(res => {
                            this.isSaveing = false;
                            if (res.error == 0) {
                                this.visible = false
                                this.$emit('success')
                                this.$notify.success("保存成功")
                            }else {
                                this.$notify.error(res.message)
                            }
                        })
                    } else {
                        await this.$API.user.action.put(this.form).then(res => {
                            this.isSaveing = false;
                            if (res.error == 0) {
                                this.visible = false
                                this.$emit('success')
                                this.$notify.success("保存成功")
                            }else {
                                this.$notify.error(res.message)
                            }
                        })
                    }
                } catch (error) {
                    this.isSaveing = false;
                }
            })
        },
        //表单注入数据
        async setData(row) {
            this.loading = true
			await this.$API.user.action.get({id: row.id}).then(res => {
                this.loading = false
                let _data = res.data
                let _form = {}
                for(let key in _data) {

                    if (key == 'agent') {
                        _form['agentId'] = _data[key] ? _data[key].id : ''
                        continue
                    }

                    if (key == 'grade') {
                        _form['gradeId'] = _data[key] ? _data[key].id : ''
                        continue
                    }

                    if (key == 'trialTeacher') {
                        _form['trialTeacherId'] = _data[key] ? _data[key].id : ''
                        continue
                    }

                    if (key == 'status') {
                        _form[key] = _data[key] ? _data[key].value : 1
                        continue
                    }

                    if (key == 'portrait') {
                        _form[key] = _data[key] ? _data[key].url : ''
                        continue
                    }

                    if (key == 'gender' || key == 'extraStudy' || key == 'learningInterest' || key == 'source') {
                        _form[key] = _data[key] ? _data[key].value != 0 ? _data[key].value : '' : ''
                        continue
                    }

                    if (key == 'chineseScore' || key == 'mathScore' || key == 'englishScore' || key == 'classRank' || key == 'gradeRank' || key == 'vocabulary' || key == 'trialDuration' || key == 'rememberWords' || key == 'accuracyRate') {
                        _form[key] = _data[key] > 0 ? _data[key] : ''
                        continue
                    }

                    if (key == 'agentId' || key == 'trialTeacherId' || key == 'gradeId') {
                        continue
                    }

                    _form[key] = _data[key]
                }
                
                this.form = _form
                
            }).finally(() => {
				this.loading = false
			})
        },
        getDefaultRuleForm() {
            return {
                id: 0,
                name: "",
                portrait: "",
                birthday: "",
                gender: 1,
                school: "",
                gradeId: "",
                mobile: "",
                password: "",
                fatherWork: "",
                motherWork: "",
                address: "",
                chineseScore: "",
                mathScore: "",
                englishScore: "",
                classRank: "",
                gradeRank: "",
                extraStudy: "",
                learningInterest: "",
                source: "",
                vocabulary: "",
                englishLevel: "",
                trialTeacherId: "",
                trialDate: "",
                trialDuration: "",
                rememberWords: "",
                accuracyRate: "",
                remark: "",
                status: 1,
                recommender: ""
            }
        },
        searchAgentHander(query) {
            this.agentLoading = true;
            this.$API.agent.listByName.get({name:query}).then((res) => {
                this.agentList = res.data
            }).finally(() => {
                this.agentLoading = false
            });
        },
        searchTeacherHander(query) {
            this.teacherLoading = true;
            this.$API.teacher.listByName.get({name:query}).then((res) => {
                this.teacherList = res.data
            }).finally(() => {
                this.teacherLoading = false
            });
        },
    }
}
</script>

<style lang="scss">
.el-tag {
    margin-left: 0 !important;
    margin-right: 10px !important;
}
::v-deep.ck.ck-editor__main>.ck-editor__editable {
    height: 200px !important;
}
</style>
